<?php

namespace app\people\controller;

use app\facade\Redis;
use app\models\{Recpeople as Recpeoples, Order, OrderGoods, RecpeopleProject, Region, RecpeopleArea, RecpeopleLog, Business, Goods, BusinessArea};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;
use think\facade\Debug;

class Recpeople extends Base
{

    public function orderlist()
    {
        $project =  (new RecpeopleProject())->where(['peoples' => $this->request->people_id, 'status' => 2])->value('goodsid');
        $project = json_decode($project, true) ?? [];
        $status = $this->request->get('status/d', 1);
        $results = (new Order())
            ->distinct(true)
            ->alias('o')
            ->join('RecpeopleArea ra', ['ra.peoples = ' . $this->request->people_id, 'ra.street = o.street', 'o.type = ra.type'])
            ->join('OrderGoods og', ['og.ordersn = o.ordersn'])
            ->field('o.id,o.name,o.ispj,o.mobile,o.lat,o.lon,o.ordersn,o.times,o.province,o.city,o.area,o.putstatus,o.street,o.getaddress,o.address,o.remark,o.status,o.type,o.tuikuan')
            ->order(['o.putstatus' => 'asc', 'o.times' => 'asc', 'o.id' => 'desc']);
        $where = [];
        $where1 = [];
        switch ($status) {
            case '1':
                $where = ['o.businessid' => $this->request->people['business'], 'o.type' => [1], 'og.goodsid' => $project, 'o.status' => 2, 'o.shouhou' => 1];
                $where1 = ['o.businessid' => $this->request->people['business'], 'o.type' => [2, 3], 'o.status' => 2, 'o.shouhou' => 1];
                break;
            case '2':
                $where = ['o.status' => 3, 'o.putorder' => $this->request->people_id];
                $where1 = ['o.status' => 3, 'o.putorder' => $this->request->people_id];
                break;
            case '3':
                $where = ['o.status' => 4, 'o.putorder' => $this->request->people_id];
                $where1 = ['o.status' => 4, 'o.putorder' => $this->request->people_id];
                break;
            case '4':
                $where = ['o.status' => [3, 4, 5], 'o.putorder' => $this->request->people_id];
                $where1 = ['o.status' => [3, 4, 5], 'o.putorder' => $this->request->people_id];
                break;
            default:
                $where = ['o.status' => -1];
                $where1 = ['o.status' => -1];
                break;
        }
        $results = $results->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->whereOr(function ($query) use ($where1) {
            $query->where($where1);
        });
        $results = $results->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            switch ($result['status']) {
                case '1':
                    $result['status_text'] = '待付款';
                    break;
                case '2':
                    $result['status_text'] = '待接单';
                    break;
                case '3':
                    $result['status_text'] = '进行中';
                    break;
                case '4':
                    $result['status_text'] = '已完成';
                    break;
                case '5':
                    $result['status_text'] = '用户已取消';
                    break;
                default:
                    $result['status_text'] = '';
                    break;
            }
            $result['province_name'] = (new Region())->where(['area_code' => $result['province'], 'level' => 1])->value('name');
            $result['city_name'] = (new Region())->where(['area_code' => $result['city'], 'level' => 2])->value('name');
            $result['area_name'] = (new Region())->where(['area_code' => $result['area'], 'level' => 3])->value('name');
            $result['street_name'] = (new Region())->where(['id' => $result['street'], 'level' => 4])->value('name');
            unset($result['province']);
            unset($result['city']);
            unset($result['area']);
            unset($result['street']);
            //配送项不进行接单权限判断，服务项要进行权限判断
            $goods = (new OrderGoods())->where('ordersn', $result['ordersn'])->field('id,images,title,name,price,number,total,goodsid,goodspecid')->select();
            foreach ($goods as $good) {
                $good['images'] = json_decode($good['images'], true);
            }
            $result['good'] = $goods;
        }

        $this->result($results, 0, '获取成功');
    }

    public function jorder()
    {
        $data = $this->request->post();
        if (empty($data['id'])) {
            $this->result([], 1, '请填写订单ID');
        }
        $order = (new Order())->where('id', $data['id'])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        if ($this->request->people['status'] != 1) {
            $this->result([], 1, '当前状态无法接单');
        }
        if ($order['status'] != 2) {
            $this->result([], 1, '订单状态不可接单');
        }
        if ($order['type'] == 1 || $order['type'] == 2 || $order['type'] == 3) {
            if ($this->request->people['business'] != $order['businessid']) {
                $this->result([], 1, '请先绑定商家');
            }
            //查询负责区域
            $area = (new RecpeopleArea())->where(['street' => $order['street'], 'type' => $order['type'], 'peoples' =>  $this->request->people_id])->find();
            if (empty($area)) {
                $this->result([], 1, '无该街道接单权限');
            }
            if ($order['type'] == 1) {
                $project = (new RecpeopleProject())->where(['peoples' => $this->request->people_id, 'status' => 2])->value('goodsid');
                $project = json_decode($project, true) ?? [];
                $goods = (new OrderGoods())->where('ordersn', $order['ordersn'])->select();
                foreach ($goods as $good) {
                    if (!in_array($good['goodsid'], $project)) {
                        $this->result([], 1, '无' . $good['title'] . '项目接单权限接单权限');
                    }
                }
            }
            $res = (new Order())->where('id', $data['id'])->update(['status' => 3, 'putorder' => $this->request->people_id, 'fwtimes' => date('Y-m-d H:i:s')]);
            if ($res) {
                $this->result([], 0, '接单成功');
            }
        } else {
            $this->result([], 1, '订单类型不可接单');
        }
    }

    public function zorder()
    {
        $data = $this->request->post();
        if (empty($data['id'])) {
            $this->result([], 1, '请填写订单ID');
        }
        if (empty($data['mobile'])) {
            $this->result([], 1, '请填写转单人账号');
        }
        $people = (new Recpeoples())->where('mobile', $data['mobile'])->find();
        if (empty($people)) {
            $this->result([], 1, '接单人不存在');
        }
        if ($people['status'] != 1) {
            $this->result([], 1, '当前状态无法接单');
        }
        if ($this->request->people_id == $people['id']) {
            $this->result([], 1, '转单人账号不能一致');
        }
        $order = (new Order())->where('id', $data['id'])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        if ($order['status'] != 3) {
            $this->result([], 1, '订单状态不可转单');
        }
        if ($order['type'] == 1 || $order['type'] == 2 || $order['type'] == 3) {
            if ($this->request->people_id != $order['putorder']) {
                $this->result([], 1, '您未拥有该订单转单权限');
            }
            if ($people['business'] != $order['businessid']) {
                $this->result([], 1, '转单人不可跨商家转单');
            }
            //查询负责区域
            $area = (new RecpeopleArea())->where(['street' => $order['street'], 'peoples' =>  $people['id']])->find();
            if (empty($area)) {
                $this->result([], 1, '转单人无该街道接单权限');
            }
            if ($data['type'] == 1) {
                $project = (new RecpeopleProject())->where(['peoples' => $people['id'], 'status' => 2])->value('goodsid');
                $project = json_decode($project, true) ?? [];
                $goods = (new OrderGoods())->where('ordersn', $order['ordersn'])->select();
                foreach ($goods as $good) {
                    if (!in_array($good['goodsid'], $project)) {
                        $this->result([], 1, '转单人无' . $good['title'] . '项目接单权限接单权限');
                    }
                }
            }
            $res = (new Order())->where('id', $data['id'])->update(['status' => 3, 'putorder' => $people['id'], 'fwtimes' => date('Y-m-d H:i:s')]);
            if ($res) {
                $this->result([], 0, '转单成功');
            }
        } else {
            $this->result([], 1, '订单类型不可接单');
        }
    }

    public function info()
    {
        $result = $this->request->people;
        unset($result['password']);
        $result['business_name'] = (new Business())->where('id', $result['business'])->value('title') ?? '';
        $result['order'] = (new Order())->where(['businessid' => $result['business'], 'putorder' => $result['id'], 'status' => [3, 4]])->count();
        $result['todayorder'] =  (new Order())->whereBetweenTime('fwtimes', date('Y-m-d') . ' 00:00',  date('Y-m-d') . ' 23:59')
            ->where(['businessid' => $result['business'], 'putorder' => $result['id'], 'status' => [3, 4]])->count();
        $this->result($result, 0, '获取成功');
    }

    public function peopleproject()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'goodsid' => 'require',
            ], [
                'goodsid.require' => '服务项目不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $haves = (new RecpeopleArea())->where(['peoples' => $this->request->people_id])->find();
            if (empty($haves)) {
                $this->result([], 1, '您不存在服务项目地区，请先添加服务项目地区');
            }
            $haves = (new RecpeopleArea())->where(['peoples' => $this->request->people_id, 'type' => 1])->find();
            if (empty($haves)) {
                $this->result([], 1, '非技师类型人员无需添加服务项目');
            }
            $goodsid = json_decode($data['goodsid'], true) ?? [];
            if (count($goodsid) <= 0) {
                $this->result([], 1, '请选择至少一个服务项');
            }
            $project = (new RecpeopleProject())->where(['peoples' => $this->request->people_id])->find();
            if (empty($project)) {
                $res = (new RecpeopleProject())->save(['peoples' => $this->request->people_id, 'goodsid' => $data['goodsid'], 'status' => 2]);
            } else {
                $res = (new RecpeopleProject())->save(['peoples' => $this->request->people_id, 'goodsid' => $data['goodsid']], ['id' => $project['id']]);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            $result = (new RecpeopleProject())->where(['peoples' => $this->request->people_id])->value('goodsid');
            $result = json_decode($result, true) ?? [];
            $this->result($result, 0, '操作成功');
        }
    }

    public function orderfinish()
    {
        $data = $this->request->post();
        if (empty($data['id'])) {
            $this->result([], 1, '请填写订单ID');
        }
        $order = (new Order())->where(['id' => $data['id'], 'putorder' => $this->request->people_id, 'status' => 3])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在或状态无法标记');
        }
        $res = (new Order())->where('id', $data['id'])->update(['putstatus' => 2, 'puttime' => date('Y-m-d H:i:s')]);
        if ($res) {
            $this->result([], 0, '标记成功');
        }
    }

    public function getbusiness()
    {
        $id = $this->request->get('id/d', 0);
        $status = $this->request->get('status/d', 1);
        if ($status == 1) {
            $result = (new Business())->where('id', $id)->field('title,descs,id,logo,mobile')->find();
            $result['order'] = (new Order())->where(['businessid' => $id, 'status' => [3, 4]])->count();
            $result['ozhi'] = (new Recpeoples())->where(['business' => $id, 'status' => [1, 2]])->count();
        } else {
            $result = (new Goods())->alias('g')
                ->join('plat_class c', 'g.classid= c.id')->where(['g.type' => [1, 2, 3], 'c.isshow' => 1, 'g.businessid' => $id, 'g.isSale' => 1, 'g.isdel' => 1])->field('g.id,g.title')->select();
        }
        $this->result($result, 0, '获取成功');
    }

    public function peoplearea()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'street' => 'require',
                'type' => 'require|in:1,2'

            ], [
                'street.require' => '街道ID不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $street = (new Region())->where(['id' => $data['street'], 'level' => 4])->find();
            if (empty($street)) {
                $this->result([], 1, '街道信息错误');
            }
            $area = (new Region())->where(['id' => $street['parent_id'], 'level' => 3])->find();
            if (empty($area)) {
                $this->result([], 1, '区域信息错误');
            }
            $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
            if (empty($area)) {
                $this->result([], 1, '城市信息错误');
            }
            $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
            if (empty($area)) {
                $this->result([], 1, '省份信息错误');
            }
            $data['street'] = $street['id'];
            $data['area'] = $area['area_code'];
            $data['city'] = $city['area_code'];
            $data['province'] = $province['area_code'];
            $data['peoples'] = $this->request->people_id;
            //判断是否超出商家运营范围
            $bussarea = (new BusinessArea())->whereOr(function ($query) use ($data) {
                $query->where(['type' => 2, 'city' => $data['city'], 'businessid' => $this->request->people['business']]);
            })->whereOr(function ($query) use ($data) {
                $query->where(['type' => 3, 'area' => $data['area'], 'businessid' => $this->request->people['business']]);
            })->whereOr(function ($query) use ($data) {
                $query->where(['type' => 4, 'street' => $data['street'], 'businessid' => $this->request->people['business']]);
            })->find();
            if (empty($bussarea)) {
                $this->result([], 1, '服务区域不在商家服务范围');
            }
            //查找是否已添加
            $haves = (new RecpeopleArea())->where(['street' => $data['street'], 'type' => $data['type'], 'peoples' => $this->request->people_id])->find();
            if (empty($data['id'])) {
                if (!empty($haves)) {
                    $this->result([], 1, '该区域当前服务类型已经添加');
                }
                $res = (new RecpeopleArea())->save($data);
            } else {
                if (!empty($haves) && $data['id'] != $haves['id']) {
                    $this->result([], 1, '该区域当前服务类型已经添加');
                }
                $res = (new RecpeopleArea())->save($data, ['id' => $data['id']]);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            $result = (new RecpeopleArea())->where(['peoples' => $this->request->people_id])->field('created,peoples', true)->select();
            foreach ($result as $results) {
                $results['province_name'] = (new Region())->where(['area_code' => $results['province'], 'level' => 1])->value('name');
                $results['city_name'] = (new Region())->where(['area_code' => $results['city'], 'level' => 2])->value('name');
                $results['area_name'] = (new Region())->where(['area_code' => $results['area'], 'level' => 3])->value('name');
                $results['street_name'] = (new Region())->where(['id' => $results['street'], 'level' => 4])->value('name');
            }
            $this->result($result, 0, '操作成功');
        }
    }

    public function joinbusiness()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require'

        ], [
            'code.require' => '邀请码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if ($this->request->people['business'] > 0) {
            $this->result([], 1, '您已绑定商家，请先解绑');
        }
        $id = $data['code'] - 568921;
        $business = (new Business())->where(['id' => $id, 'status' => 1])->find();
        if (empty($business)) {
            $this->result([], 1, '商家不存在或邀请码错误');
        }
        //查询有没有申请记录
        $reclog = (new RecpeopleLog())->where(['peopleid' => $this->request->people_id, 'status' => 1])->find();
        if (empty($reclog)) {
            $res = (new RecpeopleLog())->save(['peopleid' => $this->request->people_id, 'status' => 1, 'business' => $business['id']]);
        } else {
            $res = (new RecpeopleLog())->save([
                'peopleid' => $this->request->people_id,
                'status' => 1, 'business' => $business['id']
            ], ['id' => $reclog['id']]);
        }
        if ($res) {
            $this->result([], 0, '申请成功，请等待商家审核');
        }
        $this->result([], 1, '操作失败');
    }

    public function unjoinbusiness()
    {
        if ($this->request->people['business'] == 0) {
            $this->result([], 1, '您未绑定商家，无需解绑');
        }
        Db::startTrans();
        try {
            (new Recpeoples())->where('id', $this->request->people_id)->update(['status' => 3, 'business' => 0]);
            (new RecpeopleArea())->where(['peoples' => $this->request->people_id])->delete();
            (new RecpeopleProject())->where(['peoples' => $this->request->people_id])->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '操作失败，请重试');
        }
        $this->result([], 0, '操作成功');
    }

    public function authpeople()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'name' => 'require',
            'cards' => 'require',
            'observe' => 'require',
            'rbserve' => 'require',

        ], [
            'name.require' => '姓名不能为空',
            'cards.require' => '身份证信息不能为空',
            'observe.require' => '身份证正面不能为空',
            'rbserve.require' => '身份证反面不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $res = (new Recpeoples())->where('id', $this->request->people_id)->update(['name' => $data['name'], 'cards' => $data['cards'], 'observe' => $data['observe'], 'rbserve' => $data['rbserve']]);
        if ($res) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function register()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require',
            'name' => 'require',
        ], [
            'mobile.require' => '账号不能为空',
            'password.require' => '账号密码不能为空',
            'name.require' => '账号密码不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $people = (new Recpeoples())->where('mobile', $data['mobile'])->find();
        if (!empty($people)) {
            $this->result([], 1, '账号已存在');
        }
        $res = (new Recpeoples())->allowfield(true)->save(['mobile' => $data['mobile'], 'name' => $data['name'], 'password' => md5(md5($data['password']))]);
        if ($res) {
            $this->result([], 0, '注册成功');
        }
        $this->result([], 1, '注册失败');
    }

    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ], [
            'mobile.require' => '账号不能为空',
            'password.require' => '账号密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $people = (new Recpeoples())->where('mobile', $data['mobile'])->find();
        if (empty($people)) {
            $this->result([], 1, '账号不存在');
        }
        if ($people['password'] != md5(md5($data['password']))) {
            $this->result([], 1, '账号密码错误');
        }
        $token = 'people_' . md5(time() . $people['id']);
        Redis::setex($token, 7 * 86400, $people['id']);
        $this->result(['token' => $token], 0, '登录成功');
    }
}
